const app = getApp();
// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    shippingCarInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init()
    var cartList = wx.getStorageSync("cartList");
    this.setData({
      cartList: cartList, 
    })
  },

  init(){
    var _this = this
    app.getCategory().then(data => {
      if(data.allCategory.length === 0){
        data.allCategory.push({categoryName: "", categorySort: 1})
      }else{
        data.allCategory = data.allCategory.filter(item => item.status == 0);
      }
      _this.setData({
        categoryList: data.allCategory, 
      })
      var activeKey = _this.data.activeKey;
      if(activeKey != null){
        _this.switchSidebar(activeKey);
      }else{
        _this.switchSidebar(0);
      }
    });
  },

  switchSidebar(index){
    var _this = this
    var categoryList = _this.data.categoryList;
    var categoryName = categoryList[index].categoryName;
    var categoryId = categoryList[index].categoryId;
    var status = categoryList[index].status;
    _this.setData({ 
      activeKey: index, 
      categoryName: categoryName, 
      categoryId: categoryId , 
      status: status 
    });
    if(categoryId != null && categoryId != undefined){
      _this.queryGoodsByCategoryId(categoryId);
    }
  },

  queryGoodsByCategoryId(categoryId){
    var _this = this;
    app.request('/goods/getBy/' + categoryId, 'GET', {})
    .then(data => {
      if (data.code === 0) {
        var goodsList = data.goodsList;
        for(var i = 0; i < goodsList.length; i++){
          goodsList[i].goodsImg = app.getFileUrl(goodsList[i].goodsImg)
          goodsList[i].num = 0
        }
        _this.setData({
          goodsList: goodsList
        })
        _this.syncNum()
      } else {
        wx.showToast({
          title: data.msg || '请求失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error(err)
      wx.showToast({
        title: '服务繁忙',
        icon: 'none'
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init()
    var cartList = wx.getStorageSync("cartList");
    this.setData({
      cartList: cartList, 
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/pages/user/index?openId=432432432',
      imageUrl: 'https://yiufungcn.github.io/img/dragonCafe/logo.png'
    }
  },

  /**
   * 跳转到支付
   */
  goPay(){
    var openId = wx.getStorageSync('openId');
    if(app.isEmptyString(openId)){
      app.wxLogin()
    }
    wx.navigateTo({
      url: '/pages/index/confirmOrder/confirmOrder',
    })
  },

  showCartPop() {
    if (this.data.scanDining) {
      // 扫码点餐，前往购物车页面
      wx.navigateTo({
        url: '/pages/cart/index',
      })
    } else {
      this.setData({
        showCartPop: !this.data.showCartPop
      })
    }
  },

  onSidebarChange(event){
    var _this = this
    var index = event.detail; // 当前选中的索引
    _this.switchSidebar(index);
  },

  /**
   * 更新选择
   */
  updateSelected(goodsId, goodsName, goodsPrice, goodsImg, categoryId, optionNum){
    var _this = this 
    var cartList = _this.data.cartList
    if(!cartList){
      cartList = []
    }
    // 获取对应对象，如果没有添加一个
    var index = -1;
    for(var i = 0; i < cartList.length; i++){
      if(cartList[i].goodsId == goodsId){
        index = i;
        break
      }
    }
    if(index >= 0){
      var num = cartList[index].num;
      num += optionNum
      if(num > 0){
        cartList[index].num = num
      }
      if(num == 0){
        cartList.splice(index, 1);
      }
    }else if(optionNum == 1){
      cartList.push({goodsId:goodsId, goodsName:goodsName, goodsPrice:goodsPrice, categoryId:categoryId, num:optionNum, goodsImg: goodsImg})
    }
    _this.setData({
      cartList: cartList
    })
    wx.setStorageSync("cartList", cartList);
    _this.syncNum()
  },

  /**
   * 同步数字
   */
  syncNum(){
    var _this = this 
    var cartList = _this.data.cartList
    if(!cartList){
      return
    }
    var goodsList = _this.data.goodsList
    var categoryList = _this.data.categoryList
    var shippingCarInfo = _this.data.shippingCarInfo
    var goodsIdMap = new Map();
    var categoryIdMap = new Map();
    cartList.forEach(item => {
      goodsIdMap.set(item.goodsId, item);
      var cateList = categoryIdMap.get(item.categoryId)
      if (!cateList) {
        cateList = [];
      }
      cateList.push(item);
      categoryIdMap.set(item.categoryId, cateList);
    });
    for(var i = 0; i < goodsList.length; i++){
      var goods = goodsIdMap.get(goodsList[i].goodsId)
      if(goods != null && goods != undefined){
        goodsList[i].num = goods.num
      }else{
        goodsList[i].num = 0;
      }
    }
    for(var i = 0; i < categoryList.length; i++){
      var cateList = categoryIdMap.get(categoryList[i].categoryId)
      var cateNum = 0;
      if(cateList){
        cateList.forEach(item => {
          cateNum += item.num
        })
      } 
      if(cateNum > 0){
        categoryList[i].num = cateNum
      }else{
        categoryList[i].num = null
      }
    }
    var totalNum = 0;
    var totalPrice = 0;
    cartList.forEach(item => {
      totalNum += item.num
      totalPrice += item.goodsPrice * item.num
    });
    if (isNaN(totalPrice) || totalPrice === null || totalPrice === '') {
      totalPrice = "0.00";
    }
    totalPrice = parseFloat(totalPrice).toFixed(2);
    shippingCarInfo.totalNum = totalNum
    shippingCarInfo.totalPrice = totalPrice
    _this.setData({
      cartList: cartList,
      shippingCarInfo: shippingCarInfo,
      goodsList: goodsList,
      categoryList: categoryList
    })
  },


  addCart(e){
    var _this = this
    var idx = e.currentTarget.dataset.idx
    var goodsList = _this.data.goodsList
    var goods = goodsList[idx]
    _this.updateSelected(goods.goodsId, goods.goodsName, goods.goodsPrice, goods.goodsImg, goods.categoryId, 1)
  },

  minusCart(e){
    var _this = this
    var idx = e.currentTarget.dataset.idx
    var goodsList = _this.data.goodsList
    var goods = goodsList[idx]
    _this.updateSelected(goods.goodsId, goods.goodsName, goods.goodsPrice, goods.goodsImg, goods.categoryId, -1)
  }
})